package com.fjec.market.schedule.handler;

import com.fjec.common.schedule.BaseScheduleHandler;
import com.fjec.common.util.JsonUtil;
import com.fjec.market.service.IBizPhysicalOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单过期处理补偿线程
 */
@Slf4j
@Component
public class PhyOrderTimeoutHandler extends BaseScheduleHandler {

    @Resource
    private IBizPhysicalOrderService orderService;
    /**
     * 过期时间，单位分钟
     */
    @Value("${fjec.market.order.timeout.value}")
    private Integer timeout;

    public String handle(int limit, int minutes) {
        List<Map<String, Object>> errorList = new ArrayList<>();
        // 查询过期订单
        List<Long> orderIdList = orderService.getTimeoutOrder(limit, timeout + minutes);
        // 处理过期订单
        int success = 0;
        for (Long orderId : orderIdList) {
            try {
                orderService.handleOrderTimeout(orderId);
                success++;
            } catch (Exception ex) {
                String guid = this.error(ex);
                Map<String, Object> errorMap = new HashMap<>();
                errorMap.put("guid", guid);
                errorMap.put("id", orderId);
                errorList.add(errorMap);
            }
        }
        String result;
        if (errorList.isEmpty()) {
            // 全部处理，无异常
            result = String.format("Handle timeout order num:[%d]", success);
        } else {
            result = String.format("Handle timeout order success num:[%d], fail:[%d], Ids:[%s]",
                    success, errorList.size(), JsonUtil.toJson(errorList));
        }
        return result;
    }
}
